package com.ohuang.eventbus;


import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;


class HandlerPoster extends Handler implements Poster {
    private final PendingPostQueue queue;
    private final Bus eventBus;
    private final int maxRunTime;
    private boolean handlerActive = false;

    HandlerPoster(Looper looper, Bus bus, int maxRunTime) {
        super(looper);
        this.eventBus = bus;
        this.maxRunTime = maxRunTime;
        queue = new PendingPostQueue();
    }

    @Override
    public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            queue.enqueue(pendingPost);
            if (!handlerActive) {
                handlerActive = true;
                dispatchMessage(Message.obtain());

            }
        }
    }

    @Override
    public void handleMessage(@NonNull Message msg) {
        super.handleMessage(msg);
        boolean rescheduled = false;
        try {
            long started = System.currentTimeMillis();
            while (true) {
                PendingPost pendingPost = queue.poll();
                if (pendingPost == null) {
                    synchronized (this) {
                        // Check again, this time in synchronized
                        pendingPost = queue.poll();
                        if (pendingPost == null) {
                            handlerActive = false;
                            return;
                        }
                    }
                }
                eventBus.invokeSubscriber(pendingPost);
                long timeInMethod = System.currentTimeMillis() - started;
                if (timeInMethod >= maxRunTime) {
                    dispatchMessage(Message.obtain());
                    rescheduled = true;
                    return;
                }
            }
        } finally {
            handlerActive = rescheduled;
        }
    }



}
